package com.wifi.a007.wifiFragment;



import android.app.Notification;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/7/1.
 */

public class NetScan {
    private static final String TAG="scansssss";
    private static final int CORE_POOL_SIZE =1;
    private static final int MAX_IMUM_POOL_SIZE=255;
    private String mDevAddress;//localip
    private String mLocAddress;
    private Runtime mRun=Runtime.getRuntime();
    private Process mProcess=null;
    private String  mPing="ping -c 1 -w 3 ";
    private List<String> mIpList=new ArrayList<>();
    private ThreadPoolExecutor mExecutor;
    private int time=3;
    private String pingType="1";
    private int getCount=256;
    private StringBuilder resultString=new StringBuilder();
    private Handler handler;


    public NetScan(Handler handler) {
        this.handler = handler;
    }

    public int getGetCount() {
        return getCount;
    }

    public void setGetCount(int getCount) {
        this.getCount = getCount;
    }

    public void setPingType(String pingType) {
        this.pingType = pingType;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public void scan(){

        mDevAddress=getLocAddress();
        mLocAddress=getLocAddrIndex(mDevAddress);
        Log.d("ip","this ip:"+mDevAddress);

        if(TextUtils.isEmpty(mLocAddress)){

            Log.e(TAG,"scan fail please try check network");
        }

        mExecutor=new ThreadPoolExecutor(CORE_POOL_SIZE,MAX_IMUM_POOL_SIZE,
                2000, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(CORE_POOL_SIZE));

          for(int i=1; i< getCount; i++) {

              final int lastAddress = i;
              final Runnable run = new Runnable() {
                  @Override
                  public void run() {
                    String ping ;
                      //if(pingType.equals("1")){

                        //  ping ="ping -c 3 -w "+time+" 192.168.201.4";
                     // }else{

                          ping= "ping -c 3 -w "+time+" "+ mLocAddress + lastAddress;
                     // }
                     //mPing + mLocAddress + lastAddress;
                      Log.i("ping string",ping);
                      String currnetIp = mLocAddress + lastAddress;
                      if (mDevAddress.equals(currnetIp)) {

                          return;
                      }
                      try {
                          mProcess = mRun.exec(ping);

                          int result = mProcess.waitFor();
                         // Log.d(TAG, "当前扫的ip为：" + currnetIp + "返回值:" + result);
                          if (result == 0) {

                              resultString.append(currnetIp+"\n");
                              //Log.d(TAG, "success ip address is:" + currnetIp);

                          }

                      } catch (Exception e) {

                          e.printStackTrace();
                      } finally {
                          if (mProcess != null) {

                              mProcess.destroy();
                          }
                      }


                  }

                  ;///end run function


              };////end for run  instance
            mExecutor.execute(run);
          }//end for ;

        mExecutor.shutdown();




        while(true){


            try{
                if(mExecutor.isTerminated()){

                    Log.d(TAG,"scan is over now");
                    break;
                }

                //Log.i("waiter for thread","wait for thread");
            }catch(Exception e){

                e.printStackTrace();
            }
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){

                e.printStackTrace();
            }
        }
        resultString.append("\nok");
        Message message=new Message();
        message.what=0x007;
        message.obj=this.resultString.toString();
        handler.sendMessage(message);
        destroy();


    }

    public void destroy(){///>>>


        if(mExecutor != null){

            mExecutor.shutdownNow();
        }

    }


    private String getLocAddress(){

        String ipaddress="";
        try{

            Enumeration<NetworkInterface> enumeration =  NetworkInterface.getNetworkInterfaces();


            while(enumeration.hasMoreElements()){

                NetworkInterface networks=enumeration.nextElement();
                Enumeration<InetAddress> address= networks.getInetAddresses();
                while(address.hasMoreElements()){

                    InetAddress ip=address.nextElement();
                    if(!ip.isLoopbackAddress() &&  ip instanceof  Inet4Address){

                            return ip.getHostAddress();
                    }
                }

            }


        }catch (Exception e){

            e.printStackTrace();
        }

        return "";
    }



    private String getLocAddrIndex(String mDevAddress){

        if(!mDevAddress.equals("")){

            return mDevAddress.substring(0,mDevAddress.lastIndexOf(".")+1);
        }
        return null;
    }


    public String getPingType() {
       String ping="";
      if(pingType.equals("1")){

          ping ="ping -c 3  -w "+time+" 192.168.201.4";
      }else{

          ping ="ping -c 3  -w "+time+" 192.168.201.4";
      }


        return pingType;
    }
    public static String  getGetWay(Context context) {
        WifiManager  wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo di = wm.getDhcpInfo();
        long getewayIpL = di.gateway;
        String getwayIpS = long2ip(getewayIpL);//网关地址
       // long netmaskIpL = di.netmask;
        //String netmaskIpS = long2ip(netmaskIpL);//子网掩码地址

        return getwayIpS;
    }


    public static String long2ip(long ip){
        StringBuffer sb=new StringBuffer();
        sb.append(String.valueOf((int)(ip&0xff)));
        sb.append('.');
        sb.append(String.valueOf((int)((ip>>8)&0xff)));
        sb.append('.');
        sb.append(String.valueOf((int)((ip>>16)&0xff)));
        sb.append('.');
        sb.append(String.valueOf((int)((ip>>24)&0xff)));
        return sb.toString();
    }
}
